import { getProjectList, createProject, deleteProject } from '@/axios/taskBoard';
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
export interface ProjectsState {
  projects: ProjectList;
  error: string | undefined;
  loading: boolean;
  status: 'idle' | 'loading' | 'error' | 'success';
  selectedProjectId: string;
}

const initialState: ProjectsState = {
  projects: [],
  error: undefined,
  loading: false,
  status: 'idle',
  selectedProjectId: ''
};

export const getProjects = createAsyncThunk<ProjectList>('projects/getProject', async () => {
  const response = await getProjectList();
  return response;
});

type PostResponseProject = PostRequest & { data: ProjectListItem };
export const addProject = createAsyncThunk<PostResponseProject, { value: string }>(
  'projects/createProject',
  async ({ value }) => {
    const response = await createProject({ params: { name: value } });
    return response;
  }
);

export const removeProject = createAsyncThunk('projects/removeProject', async (id: string) => {
  const response = await deleteProject({ params: { project_id: id } });
  return { response, id };
});

const setInitialSelectedProject = (state: ProjectsState, projects: ProjectList) => {
  const savedProjectId = localStorage.getItem('selectedProjectId');
  if (savedProjectId && projects.find((project) => project.id === savedProjectId)) {
    state.selectedProjectId = savedProjectId;
  } else if (projects.length > 0) {
    state.selectedProjectId = projects[0].id;
    localStorage.setItem('selectedProjectId', projects[0].id);
  }
};

const projectsSlice = createSlice({
  name: 'projects',
  initialState,
  reducers: {
    setSelectedProject: (state, action) => {
      state.selectedProjectId = action.payload;
      localStorage.setItem('selectedProjectId', action.payload);
    }
  },
  extraReducers: (builder) => {
    builder
      .addCase(getProjects.pending, (state) => {
        state.loading = true;
        state.status = 'loading';
      })
      .addCase(getProjects.fulfilled, (state, action) => {
        state.projects = action.payload;
        state.status = 'success';
        state.loading = false;

        setInitialSelectedProject(state, action.payload);
      })
      .addCase(getProjects.rejected, (state, action) => {
        state.status = 'error';
        state.loading = false;
        state.error = action.error.message;
      })
      .addCase(addProject.fulfilled, (state, action) => {
        if (action.payload) state.projects.unshift(action.payload.data);
        state.selectedProjectId = action.payload.data.id
        localStorage.setItem('selectedProjectId', action.payload.data.id);
      })
      .addCase(removeProject.fulfilled, (state, action) => {
        action.payload.id;
        state.projects = state.projects.filter((project) => {
          if (project.id !== action.payload.id) {
            return true;
          }
        });
        state.selectedProjectId = state.projects[0].id;
        localStorage.setItem('selectedProjectId', state.projects[0].id);
      });
  }
});

export const { setSelectedProject } = projectsSlice.actions;

export default projectsSlice.reducer;
